'use strict';

const BaseService = require('../base');
const wxConfig = require("../../../config/wx");
const WXBizDataCrypt = require('../../../config/WXBizDataCrypt');
const axios = require('axios');

class RouterService extends BaseService {
  static get modelName() {
    return 'Business.User';
  }
  // 微信授权一键登录
  async wxLogin(data) {
    const { code, encryptedData, iv, parent_user_id } = data;
    try {
      const { openid, session_key } = await this.exchangeCodeForSessionKey(code)
      const phone = this.decryptPhoneNumber(session_key, encryptedData, iv)
      return await this.loginForm(openid, phone, parent_user_id)
    } catch (error) {
      console.log(error)
      throw new Error(error);
    }
  }
  async update(id, data) {
    let parentUser = null
    let user_type = null
    if (data.parent_user_id) {
      parentUser  = await this.model.findOne({
        where: {
          id: data.parent_user_id
        }
      })
    }
    if (parentUser) {
      //  '1 普通用户 2 商家 3 一级分销商 4 二级分销商'
      const userTypeMap = {
        1: 1,
        2: 3,
        3: 4,
        4: 1
      }
      user_type = userTypeMap[parentUser.user_type || 1]
    }
    let _data = {
      ...data
    }
    if (user_type) {
      _data = {
        ..._data,
        user_type
      }
    }
    return await super.update(id, _data)
  }
  async loginForm(openid, phone, parent_user_id = 0) {
    const { User } = this.ctx.model.Business;
    // 根据手机号查询用户是否存在
    let user = await User.findOne({
      where: {
        phone
      },
    });
    let parentUser = null
    let user_type = 1
    if (parent_user_id) {
      parentUser  = await User.findOne({
        where: {
          id: parent_user_id
        }
      })
    }
    if (parentUser) {
      //  '1 普通用户 2 商家 3 一级分销商 4 二级分销商'
      const userTypeMap = {
        1: 1,
        2: 3,
        3: 4,
        4: 1
      }
      user_type = userTypeMap[parentUser.user_type || 1]
    }
    if (!user) {
      // 去注册
      let createUser = await User.create({
        password: '123456',
        openid,
        phone,
        nickname: '用户' + new Date().getTime(),
        avatar_url: '/static/images/user.png',
        user_type: user_type,
        parent_user_id: parent_user_id || 0,
      })
      let userValue = createUser.dataValues;
      delete userValue.password;
      return userValue;
    } else {
      if (!user.openid) {
        let updateData = {
          openid,
        }
        if (parent_user_id) {
          updateData.parent_user_id = parent_user_id
          updateData.user_type = user_type
        }
        await user.update(updateData, {
          where: {
            id: user.id
          }
        })
      }

      const _user = await User.findOne({
        where: {
          id: user.id
        },
        include: [
          {
            model: this.ctx.model.Business.User,
            as: 'parent'
          }
        ]
      })
      return  _user.dataValues
    }
  }

  async getUserQrCode(data) {
    // 邀请码查重
    const hasInvite = await this.model.findOne({ where: { id: data.user_id } })
    if (!hasInvite) {
      throw new Error('用户不存在');
    }
    if (hasInvite.invite_qr_code) {
      return hasInvite.invite_qr_code
    }
    let base64 = ''
    try {
      const tokenRes = await this.ctx.curl(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${wxConfig.appid}&secret=${wxConfig.secret}`, { method: 'GET', dataType: 'json' });
      const token = tokenRes.data.access_token
      if (tokenRes.data.errcode) {
        throw new Error(tokenRes.data.errmsg);
      }
      const requestData = {
        path: 'pages/index/index?user_id=' + data.user_id,
        width: 430,
        env_version: 'trial'
      }
      const qcodeRes = await axios({
        url: `https://api.weixin.qq.com/wxa/getwxacode?access_token=${token}`,
        method: 'POST',
        data: requestData,
        responseType: 'arraybuffer',
      });
      const result = await this.ctx.service.common.upload.uploadCos(qcodeRes.data, data.user_id + '.jpg')

      base64 = 'https://' + result.Location
      await this.model.update({
        invite_qr_code: base64
      }, {
        where: {
          id: data.user_id
        }
      })
      return base64
    }
    catch (e) {
      throw new Error(e);
    }
  }

  async exchangeCodeForSessionKey(code) {
    const url = `https://api.weixin.qq.com/sns/jscode2session?appid=${wxConfig.appid}&secret=${wxConfig.secret}&js_code=${code}&grant_type=authorization_code`;
    const response = await this.ctx.curl(url, { dataType: 'json' });
    const data = response.data;
    if (!data.session_key || !data.openid) {
      throw new Error('Failed to exchange code for session_key and openid');
    }
    return {
      session_key: data.session_key,
      openid: data.openid,
    };
  }
  decryptPhoneNumber(session_key, encryptedData, iv) {
    const pc = new WXBizDataCrypt(wxConfig.appid, session_key);
    const data = {};
    const errCode = pc.decryptData(encryptedData, iv, data);
    return errCode.phoneNumber
  }


  getPageInclude() {
    return [
      {
        model: this.ctx.model.Business.User,
        as: 'parent'
      }
    ]
  }

  async getChildrenList({ parent_user_id }) {
    return await this.model.findAll({
      where: {
        parent_user_id
      },
      include: [
        {
          // 分销记录
          model: this.ctx.model.Business.BalanceRecord,
          where: {
            type: 2,
          },
          as: 'balanceRecord',
          required: false
        }
      ]
    })
  }
}


module.exports = RouterService;
